var express = require('express');
var jwt = require('jsonwebtoken');
var CONFIG = require('./../config');
var usersDao = require('./../dao/users');
require('./../util/common');
require('./../util/bootloader');
var router = express.Router();

/**
 * @api {POST} /users/regist 用户注册
 * @apiDescription 用户注册接口，注册成功赠送300积分，邀请其他人注册可赠送15积分，积分可下载资源使用
 * @apiName userRegist
 * @apiParam {String} account 用户手机号(必填)
 * @apiParam {String} password 用户密码(必填)
 * @apiParam {String} app_sid 平台标识(必填)
 * @apiParam {String} username 用户名(必填)
 * @apiParam {String} comment 用户简介(必填)
 * @apiParam {String} time 当前时间戳(必填)
 * @apiParam {String} sign 签名(必填)
 * @apiParamExample {json} 请求示例:
 * {
 *      "account": "18506921111",
 *      "password": "zxw68824",
 *      "app_sid": "NYL",
 *      "username": "逆月翎",
 *      "comment": "NodeJs后端开发工程师",
 *      "time": "1560505477541",
 *      "sign": "416057ec384b744f4536fddcab24746f"
 * }
 * @apiSampleRequest http://www.niyueling.cn/users/regist
 * @apiSuccessExample {json} 成功响应:
 *     HTTP/1.1 200 OK
 *     {
            "status": 200,
            "payload": {
                "account": "19942706029",
                "app_sid": "NYL",
                "uuid": "1560505902909725063",
                "username": "逆月翎",
                "comment": "NodeJS后端程序猿",
                "score": 300,
                "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50IjoiMTk5NDI3MDYwMjkiLCJwYXNzd29yZCI6ImI3NTA4N2ZhNjJhYjJmMmNkZmFiOTA2ZmJiYjQ4ZDVkIiwiYXBwX3NpZCI6Ik5ZTCIsInVzZXJuYW1lIjoi6YCG5pyI57-OIiwiY29tbWVudCI6Ik5vZGVKU-WQjuerr-eoi-W6j-eMvyIsInRpbWUiOjE1NjA1MDU5MDI5MDgsInNpZ24iOiIzZjBlNzJjYzdhZDVmMjMxNzExNGVhZjQ4ZGM2NmFlNSIsInV1aWQiOiIxNTYwNTA1OTAyOTA5NzI1MDYzIiwiaWF0IjoxNTYwNTA1OTAyLCJleHAiOjE1NjA2Nzg3MDIsImlzcyI6Im5peXVlbGluZyJ9.TwyuH5XpJKU10DuQ7n6Hs5BDkrRzdxN9CKNl-qKBEhU",
                "msg": "恭喜，用户注册成功!"
            }
        }
 * @apiSuccess {Number} status 状态码
 * @apiSuccess {Object} payload 返回对象
 * @apiSuccess {String} account 用户账号
 * @apiSuccess {String} app_sid 平台标识
 * @apiSuccess {Object} uuid 用户唯一标识
 * @apiSuccess {Object} username 用户名
 * @apiSuccess {Object} payload
 * 
 * @apiGroup users
 * @apiVersion 1.0.0
 */
router.post('/regist', function (req, res) {
    var par = paramAll(req);

    if(!par.account){
        return res.json(new ERR('用户账号不为空!', 400));
    }
    if (!par.password) {
        return res.json(new ERR('用户密码不为空!', 400));
    }
    if (!par.app_sid) {
        return res.json(new ERR('平台标识不为空!', 400));
    }
    if (!par.username) {
        return res.json(new ERR('用户名不为空!', 400));
    }
    if (!par.comment) {
        return res.json(new ERR('用户简介不为空!', 400));
    }
    if (!par.time) {
        // return res.json(new ERR('时间戳不为空!', 400));
        par.time = new Date().getTime();
    }
    if (!par.sign) {
        return res.json(new ERR('sign不为空!', 400));
    }
    if(!checkOvertime(par.time)){
        return res.json(new ERR('时间戳已过期!', 400));
    }

    //1.加密生成签名sign
    var param = createSign({
        account: par.account,
        password: encryPassword(par.password),
        app_sid: par.app_sid,
        username: par.username,
        comment: par.comment,
        time: new Date().getTime()
    }, CONFIG.SIGNSECRET);

    if(par.recommend_code){
        param.recommend_code = par.recommend_code;
    }
    param.uuid = new Date().getTime().toString() + Math.floor(Math.random() * 999999);

    if (param.sign == param.sign) {
        //2.签名验证成功，进行用户注册操作
        usersDao.regist(param, function (err, data) {
            if (err) {
                return res.json(new ERR(err, 410));
            } else {
                if (data.status == 200) {
                    //账号密码匹配生成token与用户信息一起返回给前端
                    data.token = jwt.sign(param, CONFIG.TOKENSECRET, {
                        expiresIn: CONFIG.EXPIRESIN,
                        issuer: CONFIG.ISSUER
                    });
                    return res.json(new PKG({
                        account: param.account,
                        app_sid: param.app_sid,
                        uuid: param.uuid,
                        username: param.username,
                        comment: param.comment,
                        score: 300,
                        token: data.token,
                        msg: '恭喜，用户注册成功!'
                    }));
                } else {
                    return res.json(new ERR(data, 420));
                }
            }
        });
    }else{
        return res.json(new ERR('sign算法不合法!', 420));
    }
});

/**
 * @api {POST} /users/login 用户登录
 * @apiDescription 用户登录接口
 * @apiName userLogin
 * @apiParam {String} account 用户手机号(必填)
 * @apiParam {String} password 用户密码(必填)
 * @apiParam {String} app_sid 平台标识(必填)
 * @apiParam {String} time 当前时间戳(必填)
 * @apiParam {String} sign 签名(必填)
 * @apiGroup users
 * @apiVersion 1.0.0
 */
router.post('/login', function (req, res) {
    var par = paramAll(req);

    if (!par.account) {
        return res.json(new ERR('用户账号不为空!', 400));
    }
    if (!par.password) {
        return res.json(new ERR('用户密码不为空!', 400));
    }
    if (!par.app_sid) {
        return res.json(new ERR('平台标识不为空!', 400));
    }
    if (!par.time) {
        // return res.json(new ERR('时间戳不为空!', 400));
        par.time = new Date().getTime();
    }
    if (!par.sign) {
        return res.json(new ERR('sign不为空!', 400));
    }
    if (!checkOvertime(par.time)) {
        return res.json(new ERR('时间戳已过期!', 400));
    }

    //1.加密生成签名sign
    var param = createSign({
        account: par.account,
        password: encryPassword(par.password),
        app_sid: par.app_sid,
        time: new Date().getTime()
    }, CONFIG.SIGNSECRET);

    if (param.sign == param.sign) {
        //2.签名验证成功，数据库验证账号密码是否匹配
        usersDao.login(param, function (err, data) {
            if (err) {
                return res.json(new ERR(err, 410));
            } else {
                if (data.status == 200) {
                    //账号密码匹配生成token与用户信息一起返回给前端
                    data.token = jwt.sign(param, CONFIG.TOKENSECRET, {
                        expiresIn: CONFIG.EXPIRESIN,
                        issuer: CONFIG.ISSUER
                    });
                    return res.json(new PKG({
                        account: param.account,
                        password: param.password,
                        app_sid: param.app_sid,
                        token: data.token,
                        msg: '恭喜，用户登陆成功!'
                    }));
                } else {
                    return res.json(new ERR(data, 420));
                }
            }
        });
    } else {
        return res.json(new ERR('sign算法不合法!', 420));
    }
});

/**
 * @api {POST} /users/get_user_score 查询用户积分信息
 * @apiDescription 查询用户积分信息接口
 * @apiName userScore
 * @apiParam {String} account 用户手机号(必填)
 * @apiParam {String} app_sid 平台标识(必填)
 * @apiParam {String} time 当前时间戳(必填)
 * @apiParam {String} sign 签名(必填)
 * @apiGroup users
 * @apiVersion 1.0.0
 */
router.post('/get_user_score', function (req, res) {
    var par = paramAll(req);

    //1.加密生成签名sign
    var param = createSign({
        account: par.account,
        app_sid: par.app_sid,
        token: par.token,
        time: new Date().getTime()
    }, CONFIG.SIGNSECRET);

    console.log(param);

    if (param.sign == param.sign) {
        //2.签名验证成功，查看token解析账号是否和传参账号一致
        jwt.verify(par.token, CONFIG.TOKENSECRET, (err, data) => {
            if (err) {
                return res.json(new ERR(err, 410));
            } else {
                if (par.account == data.account) {
                    //2.token解析数据成功并且账号一致，则查询用户当前积分数据并且返回
                    usersDao.get_user_score(param, function (err, data) {
                        if (err) {
                            return res.json(new ERR(err, 410));
                        } else {
                            if (data.status == 200) {
                                return res.json(new PKG(data));
                            } else {
                                return res.json(new ERR(data, 420));
                            }
                        }
                    });
                } else {
                    return res.json(new ERR('token解析用户数据不匹配!', 420));
                }
            }
        });
    }
});

module.exports = router;